<?php
    include "../../../config.php";
    require_once("../redirect.php");
    require_once("../config.php");
    global $FOLIO_CFG;

    Header("content-type: application/x-javascript");

    $path = $CFG->wwwroot . 'mod/folio/ajax/';
    $url = $CFG->wwwroot;

    // Get the correct fieldname for the echo var in the Redirect object.
    //      This is then passed as the name of the parameter so that
    //      the ajax pages know what to do as a resulting action.
    $redirect_echo = folio_redirect::htmlVariableName( 'echo' );

?>

// Upload file asynch thru ajax.
function init( iPage_Ident ){
    var onUploadButtonClick = function(e){
        //Set which form we're loading.
        YAHOO.util.Connect.setForm('folio_RichEditor_FileUpload_form', true);

        // Turn off form & show uploading icon
        //Effect.Fade('folio_RichEditor_FileUpload_form','appear');
        Effect.Appear('folio_RichEditor_FileUpload_uploading','appear');

        var uploadHandler = {
            upload: function(o) {

                // Reset the upload box.
                //Effect.Appear('folio_RichEditor_FileUpload_form','appear');
                Effect.Fade('folio_RichEditor_FileUpload_uploading','appear');
                folio_PageEditorAddAttachments_Menu_Reset();
                document.getElementById('folio_RichEditor_FileUpload_form').testFile.value = '';

                // Test to see if we have a valid result.
                if ( o.responseText.indexOf('|') == -1 ||
                     o.responseText.indexOf('~') == -1 ) {
                    // Tell the user of the error message.
                    alert( o.responseText );
                } else {
                    // Add the resource.
                    var sKey = o.responseText.substr( o.responseText.indexOf('|')+1, o.responseText.indexOf('~') - 1 - o.responseText.indexOf('|') );
                    var iPage = o.responseText.substr( o.responseText.indexOf('~') + 1 );

                    folio_RichEditor_AddResource( sKey, iPage );
                }

            }
        };
        YAHOO.util.Connect.asyncRequest('POST', '<?php echo $path; ?>file_insert.php', uploadHandler);
    };
    YAHOO.util.Event.on('uploadButton', 'click', onUploadButtonClick);
}


//Event.observe(window, 'load', init, false);
function folio_RichEditor_InitializeList( iPage ) {

    // Create list
    Sortable.create("folio_RichEditor_list",
        {
        dropOnEmpty:true,
        handle:"handle",
        containment:["folio_RichEditor_list"],
        constraint:false,
        onUpdate: function()
        {
            folio_RichEditor_SetOrder( iPage );
        }

        });

}

// Called by the returns from ajax postbacks to re-set the sort order, as well as
//      by the onUpdate property of the Sortable.
function folio_RichEditor_SetOrder( iPage ) {

    var poststring = Sortable.sequence('folio_RichEditor_list');

    // This doesn't actually update part of the page.  It is needed to simply
    //      set the new sort order after adding or updating the page.
    var myR = new Ajax.Updater(   'no_update_location_123_123_123', //folio_RichEditor_list
        '<?php echo $path; ?>page_update.php',
        {   insertion: Insertion.Top,
            asynchronous:false,
            evalScripts:true,
            method: 'post',
            parameters: 'page_ident='+iPage + '&<?php echo $redirect_echo; ?>=attachments' +'&content='+poststring});

}
// Called to load menu of items from the db for the left-hand side.
function folio_RichEditor_GetResources( sType, iUser, iPage ) {
    var myA = new
        Ajax.Updater('folio_resources',
            '<?php echo $path; ?>resource_select.php',
            {method: 'get', parameters: 'type='+sType+'&page_owner='+iUser+'&page_ident='+iPage});
}

// Called to setup a new resource item, moving from a resource to an item.
// ID : the id of the resource to change into an item.
function folio_RichEditor_AddResource( sKey, iPage  ) {

    Sortable.destroy("folio_RichEditor_list");

    // Load from db.  Note that this is asynch, executes returned js code.
    var myR = new Ajax.Updater(   'folio_RichEditor_list', // + id,
        '<?php echo $path; ?>artifact_insert.php',
        {   insertion: Insertion.Top,
            asynchronous:false,
            evalScripts:true,
            method: 'post',
            parameters: 'key='+sKey+'&page_ident='+iPage});

    //Effect.Fade('folio_RichEditor_working','appear');
}

// Called to setup a new resource item, moving from a resource to an item.
// ID : the id of the resource to change into an item.
function folio_Decoration_AddText( iPage  ) {

    Sortable.destroy("folio_RichEditor_list");

    // Load from db.  Note that this is asynch, executes returned js code.
    var myR = new Ajax.Updater(   'folio_RichEditor_list', // + id,
        '<?php echo $path; ?>decoration_insert.php',
        {   insertion: Insertion.Top,
            asynchronous:false,
            evalScripts:true,
            method: 'post',
            parameters: 'page_ident='+iPage+'&type=label'});

    //Effect.Fade('folio_RichEditor_working','appear');
}

// Called to setup a new resource item, moving from a resource to an item.
// ID : the id of the resource to change into an item.
function folio_Decoration_AddHtml( iPage  ) {

    Sortable.destroy("folio_RichEditor_list");
    var html = encodeURIComponent(
                document.getElementById(
                    'folio_PageEditorAddAttachments_Embed_html'
                    ).value
                );

    // Load from db.  Note that this is asynch, executes returned js code.
    var myR = new Ajax.Updater(   'folio_RichEditor_list', // + id,
        '<?php echo $path; ?>decoration_insert.php',
        {   insertion: Insertion.Top,
            asynchronous:false,
            evalScripts:true,
            method: 'post',
            parameters: 'page_ident='+iPage+'&type=html&text='+html});

    //$('folio_PageEditorAddAttachments_Embed_html') =  '';
    folio_PageEditorAddAttachments_Menu_Reset();
    //Effect.Fade('folio_RichEditor_working','appear');
}

// Called to remove a resource item
// ID : the id of the resource
function folio_RichEditor_Delete( iIdent, sType ) {

    // Remove JS element.
    Element.remove('folio_'+sType + iIdent);

    // Remove from db via ajax call.
    var myR = new Ajax.Updater(   'folio_RichEditor_list',
        '<?php echo $path; ?>'+sType+'_delete.php',
        {   insertion: Insertion.Top,
            asynchronous:false,
            evalScripts:true,
            method: 'post',
            parameters: sType+'_ident='+iIdent});

}



// Toggle visibility of object.
function folio_artifact_ToggleVisible( sElement_id, boolVisible ) {
    if ( boolVisible ) {
        Effect.Appear(sElement_id +'_text','appear');
        Effect.Fade(sElement_id+ '_expand','appear');
    } else {
        Effect.Fade(sElement_id +'_text','appear');
        Effect.Appear(sElement_id +'_expand','appear');
    }
}

// Remaining code from internet example of edit.php & scriptaculous
// http://24ways.org/2005/edit-in-place-with-ajax
//function init(){
//    makeEditable('desc');
//    makeEditable('pizza');
//}

function folio_RichEditor_makeEditable(iIdent, sType, sField, id){

    Event.observe(id, 'click', function(){folio_RichEditor_edit(iIdent, sType, sField, $(id))}, false);
    Event.observe(id, 'mouseover', function(){folio_RichEditor_showAsEditable($(id))}, false);
    Event.observe(id, 'mouseout', function(){folio_RichEditor_showAsEditable($(id), true)}, false);
}

function folio_RichEditor_makeRichEditable(iIdent, sType, sField, id){

    Event.observe(id, 'click', function(){folio_RichEditor_Richedit(iIdent, sType, sField, $(id))}, false);
    Event.observe(id, 'mouseover', function(){folio_RichEditor_showAsEditable($(id))}, false);
    Event.observe(id, 'mouseout', function(){folio_RichEditor_showAsEditable($(id), true)}, false);
}

function folio_RichEditor_edit(iIdent, sType, sField, obj){
    Element.hide(obj);

    var iRows = 1;

    var textarea = '<div id="'+obj.id+'_editor"><textarea id="'+obj.id+'_edit" name="'+obj.id+'" rows="'+iRows+'" cols="60">'+obj.innerHTML+'</textarea>';
    var button     = '<div><input id="'+obj.id+'_save" type="button" value="SAVE" /> OR <input id="'+obj.id+'_cancel" type="button" value="CANCEL" /><br/></div></div>';
    var sField = '<textarea id="'+obj.id+'_field" style="display:none;">'+sField+'</textarea>';

    new Insertion.After(obj, textarea+sField+button);

    Event.observe(obj.id+'_save', 'click', function(){folio_RichEditor_saveChanges(iIdent, sType, obj)}, false);
    Event.observe(obj.id+'_cancel', 'click', function(){folio_RichEditor_cleanUp(iIdent, sType, obj)}, false);

}

// For using tinymce as the editor.
function folio_RichEditor_Richedit(iIdent, sType, sField, obj){
    Element.hide(obj);

    var iRows = 4;

    var textarea = '<div id="'+obj.id+'_editor"><textarea id="'+obj.id+'_edit" name="'+obj.id+'" rows="'+iRows+'" cols="60">'+obj.innerHTML+'</textarea>';
    var button     = '<div><input id="'+obj.id+'_save" type="button" value="SAVE" /> OR <input id="'+obj.id+'_cancel" type="button" value="CANCEL" /><br/></div></div>';
    var sField = '<textarea id="'+obj.id+'_field" style="display:none;">'+sField+'</textarea>';

    new Insertion.After(obj, textarea+sField+button);

    Event.observe(obj.id+'_save', 'click', function(){folio_RichEditor_saveRichChanges(iIdent, sType, obj)}, false);
    Event.observe(obj.id+'_cancel', 'click', function(){folio_RichEditor_RichcleanUp(iIdent, sType, obj)}, false);

    // For firefox, set counter=0, otherwise the 2nd editor won't load.
    tinyMCE.idCounter=0;
    tinyMCE.execCommand('mceAddControl', true, obj.id);
    Element.hide(obj.id+"_edit");


}

// For using tinyMCE
//      Errors when using inside function, be sure to keep in the top level of this js file.
tinyMCE.init({
    mode:"textareas",
        plugins : 'spellchecker,emotions,contextmenu,preview,style,searchreplace,safari',
        convert_urls : false,
        relative_urls : false,
        theme : "advanced",
        theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,image,undo,redo,link,unlink,code,spellchecker,emotions",
        theme_advanced_buttons2 : "preview,styleprops,search,replace",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_path_location : "bottom",
        plugin_preview_width : "500",
        plugin_preview_height : "600",
        extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
        remove_linebreaks: true,
        theme_advanced_source_editor_width : "400",
        theme_advanced_source_editor_height : "400",
        spellchecker_languages : "en",
        document_base_url : "<?php echo $url ?>",
        width : "<?php echo ($FOLIO_CFG->page_edit_width); ?>",
        height : "<?php echo $FOLIO_CFG->page_edit_height; ?>",
        fullscreen_settings : {
            theme_advanced_path_location : "top"
        }
});

function folio_RichEditor_showAsEditable(obj, clear){
    if (!clear){
        Element.addClassName(obj, 'folio_page_editable_highlight');
        Element.removeClassName(obj, 'folio_page_editable');
    }else{
        Element.removeClassName(obj, 'folio_page_editable_highlight');
        Element.addClassName(obj, 'folio_page_editable');
    }
}


function folio_RichEditor_saveRichChanges(iIdent, sType, obj){

    var new_content    =  encodeURIComponent(tinyMCE.getContent());
    var sField =  encodeURIComponent($F(obj.id+'_field'));

    obj.innerHTML    = "Saving...";
    folio_RichEditor_RichcleanUp(iIdent, sType, obj, false);

    var success    = function(t){folio_RichEditor_editComplete(t, obj);}
    var failure    = function(t){folio_RichEditor_editFailed(t, obj);}

      var url = '<?php echo $path; ?>'+sType+'_update.php';
    var pars = sType+'_ident=' + iIdent + '&<?php echo $redirect_echo; ?>=' + sField + '&content='+new_content;
    var myAjax = new Ajax.Request(url, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});

}
function folio_RichEditor_RichcleanUp(iIdent, sType, obj, keepEditable){

    // For removing editor.
    tinyMCE.execCommand("mceRemoveControl", false, obj.id);

    Element.remove(obj.id+'_editor');
    Element.show(obj);
    if (!keepEditable) folio_RichEditor_showAsEditable(obj, true);
}


function folio_RichEditor_saveChanges(iIdent, sType, obj){

    var new_content    =  encodeURIComponent($F(obj.id+'_edit'));
    var sField =  encodeURIComponent($F(obj.id+'_field'));

    obj.innerHTML    = "Saving...";
    folio_RichEditor_cleanUp(iIdent, sType, obj, false);

    var success    = function(t){folio_RichEditor_editComplete(t, obj);}
    var failure    = function(t){folio_RichEditor_editFailed(t, obj);}

      var url = '<?php echo $path; ?>'+sType+'_update.php';
    var pars = sType+'_ident=' + iIdent + '&<?php echo $redirect_echo; ?>=' + sField + '&content='+new_content;
    var myAjax = new Ajax.Request(url, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});

}

function folio_RichEditor_cleanUp(iIdent, sType, obj, keepEditable){

    // For removing editor.
    //tinyMCE.execCommand('mceREmoveControl', true, obj.id);
    Element.remove(obj.id+'_editor');
    Element.show(obj);
    if (!keepEditable) folio_RichEditor_showAsEditable(obj, true);
}

function folio_RichEditor_editComplete(t, obj){
    obj.innerHTML    = t.responseText;
    folio_RichEditor_showAsEditable(obj, true);
}

function folio_RichEditor_editFailed(t, obj){
    obj.innerHTML    = 'Sorry, the update failed.';
    folio_RichEditor_cleanUp(obj);
}

<?php
    unset( $path );
    unset( $redirect_echo );
?>
